<?php
namespace app\api\controller;

use think\Request;
use think\controller\Rest;
use app\api\controller\Base;

/**
 *任务评论管理 
 * 
 */

class Comment extends Base
{
	
	/**
	 * 新增评论
	 *
	 * @param [array] $[ data] [评论数据]
	 * @return [json] [新增成功]
	 */
	public function add()
	{
		# 接收评论数据
		$data = input('post.');
		# 判断数据安全
		if(empty($data['task_id']))
		{
			return Base::json(400,'任务标识错误');
		}
		# 检查任务是否存在
		$taskInfo = db('task')->where('id',$data['task_id'])->find();
		if(!$taskInfo)
		{
			return Base::json(400,'任务不存在');
		}
		$data['commentator_id'] = session('User.id') ? session('User.id') : 1;
		$data['add_time'] = time();
		$data['url'] = serialize($data['url']);
		# 添加评论
		$res = db('comment')->insert($data);
		if($res)
		{
			return Base::json(200,'评论成功');
		}else{
			return Base::json(400,'评论失败');
		}

	}
	/**
	 * 评论列表
	 *
	 *@param [int] $[task_id] [任务ID]
	 *@return [json] [评论列表数据集]
	 * 
	 */
	public function commentList()
	{
		# 接收数据
		$data = input('post.');
		$uid = session('User.id') ? session('User.id') : 1;
		# 检验数据
		if(!is_numeric($data['task_id']))
		{
			return Base::json(400,'任务标识错误');
		}
		$where = "c.task_id = ".$data['task_id'];
		if(isset($data['about']) && $data['about'] == 1)
		{
			$where .= " and (c.commentator_id = ".$uid." or c.respondent_id = ".$uid.")";
		}
		$commentList = db("comment")->alias('c')->where($where)->join("users u","c.commentator_id = u.id")->field('c.*,u.id,u.name')->select();
		foreach ($commentList as $k => $val) 
		{
			$commentList[$k]['add_time'] = strtotime($commentList[$k]['add_time']);
			$commentList[$k]['time'] = Base::transTime($commentList[$k]['add_time']);
			if($commentList[$k]['respondent_id'] != 0)
			{
				$commentList[$k]['reply_name'] = db('users')->where('id',$commentList[$k]['respondent_id'])->field('name')->find();
			}
		}

		return Base::json(200,"查询成功",$commentList);
	}
	/**
	 *获取任务文件
	 *
	 * @param [int] $[task_id] [任务ID]
	 * @return [json] [数据集]
	 */
	public function filesList()
	{
		# 接收数据
		$data = input('post.');

		# 查询任务中的文件
		$taskFiles = db('task')->where('id',$data['task_id'])->field('id,url')->find();
		$taskFiles['url'] = unserialize($taskFiles['url']);
		# 查询评论中的文件
		$commentFiles = db('comment')->where('task_id',$data['task_id'])->field('id,url')->select();

		foreach ($commentFiles as $k => $val) {
			if(array_key_exists('url',$commentFiles[$k]))
			{
				$commentUrl = unserialize($commentFiles[$k]['url']);
				foreach ($commentUrl as $k => $val) {
					$taskFiles['url'][] = $val;
				}
			}
		}

		$Url = $taskFiles['url'];

		return Base::json(200,'查询成功',$Url);
	}
}